package com.shushan.service;

import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.fgchecker.AppChecker;
import com.shushan.base.Constants;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.LockScreenWindowManager;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;

/**
 * @ClassName: FlymeForegroundService
 * @Desciption: 魅族前台监控服务
 * @author: yichaohua
 * @date: 2018-06-28
 */
public class FlymeForegroundService extends Service {

    private final static String TAG = "FlymeForegroundService";

    private AppChecker appChecker;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG,"onCreate()");

        startChecker();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand()");

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(appChecker != null){
            appChecker.stop();
        }

    }

    private void startChecker() {
        appChecker = new AppChecker();
        appChecker.when(getPackageName(), new AppChecker.Listener() {
                    @Override
                    public void onForeground(String packageName) {
                        Log.i(TAG, "Our app is in the foreground.");
                    }
                })
                .whenOther(new AppChecker.Listener() {
                    @Override
                    public void onForeground(String packageName) {
                        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                        boolean isLockScreenAvailable = LockScreenWindowManager.isLockScreenAvailable();
                        Log.i(TAG, "isChildControl=" + isChildControl + " isLockScreenAvailable="
                                + isLockScreenAvailable);

                        if(isChildControl && !isLockScreenAvailable){
                            BabyApplication babyApplication = BabyApplication.getInstance();
                            SystemUtils.sendForegActivity(babyApplication,TabHomeActivity.class);
                        }

                    }
                })
                .timeout(3000)
                .start(this);
    }
}
